﻿using Microsoft.Extensions.Configuration;
using SimpleInOutControl.DBModels;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;

namespace SimpleInOutControl.InitDatabase
{
    /// <summary>
    /// 数据库操作
    /// </summary>
    public static class DataBaseHelper
    {
        /// <summary>
        /// 读取配置文件种连接数据库字符串
        /// </summary>
        /// <returns></returns>
        private static string GetConnectString()
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddEnvironmentVariables();

            IConfigurationRoot configuration = builder.Build();
            var connectStr = configuration.GetConnectionString("Default") ?? "";
            return connectStr;
        }

        /// <summary>
        /// 获取SqlSugarClient对象
        /// </summary>
        /// <returns></returns>
        private static SqlSugarClient GetSqlSugarClient()
        {
            string connectStr = GetConnectString();
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = connectStr,
                DbType = DbType.MySql,
                LanguageType = LanguageType.English,
                IsAutoCloseConnection = true,
            };
            SqlSugarClient client = new SqlSugarClient(connectionConfig);
            return client;
        }
        /// <summary>
        /// 数据库优先
        /// </summary>
        public static void DbFirst()
        {
            using (var client = GetSqlSugarClient())
            {
                client.DbFirst.CreateClassFile("F:\\works\\SimpleInOutControl\\SimpleInOutControl.DBModels", "SimpleInOutControl.DBModels");

                //    //client.DbFirst.CreateClassFile("F:\\works\\smartranch\\SmartRanchApi\\YuHan.SmartRanch.DBModels", "YuHan.SmartRanch.DBModels");
                //    client.DbFirst.CreateClassFile("F:\\works\\smartranch\\SmartRanchApi\\YuHan.SmartRanch.Entities\\DBModels", "YuHan.SmartRanch.Models.DBModels");

            }
        }
        /// <summary>
        /// 代码优先，创建数据库及表
        /// </summary>
        public static void CodeFirst()
        {
            using (var client = GetSqlSugarClient())
            {
                #region 创建数据库（有数据库则跳过）
                //创建数据库（有数据库则跳过）
                client.DbMaintenance.CreateDatabase();
                #endregion

                #region 创建单个表
                //创建单个表
                //client.CodeFirst.InitTables(typeof(SubSystem));
                //client.CodeFirst.SetStringDefaultLength(50).InitTables(typeof(SubSystem));
                #endregion

                #region 批量创建表
                ////var assembly = Assembly.LoadFrom("YuHan.SmartRanch.DBModels.dll");
                var assembly = typeof(UserInfo).Assembly;
                var types = assembly.GetTypes()//.Where(it => it.FullName.Contains(""))
                    .ToArray();
                client.CodeFirst.InitTables(types);
                #endregion

            }
        }
        /// <summary>
        /// 初始化数据
        /// </summary>
        public static void InitData()
        {
            using (var client = GetSqlSugarClient())
            {
                #region 系统参数
                client.DbMaintenance.TruncateTable<SystemParameter>();
                client.Insertable(new SystemParameter()
                {
                    ID = 0,
                    Capacity = 80,
                    EarlyWarningAmount = 70,
                    ValidNotEntered = 120
                }).ExecuteCommand();
                #endregion

                #region 操作员
                client.DbMaintenance.TruncateTable<UserInfo>();
                client.Insertable(new UserInfo()
                {
                    ID = 0,
                    Name = "管理员",
                    Password = "123456",
                }).ExecuteCommand();
                #endregion

            }
        }
    }
}
